package controllers

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
	"time"

	"monitor/models"

	"github.com/astaxie/beego"
)

type MonitorController struct {
	beego.Controller
}

func (this *MonitorController) Post() {
	this.Get()
}

func (this *MonitorController) Get() {
	app := this.GetString("app")
	host := this.GetString("host")
	name := this.GetString("name")
	interval, _ := this.GetInt("time")
	params := this.GetString("params")

	if interval == 0 {
		interval = 10
	}

	maps := map[string]string{}
	keys := make([]string, 0)

	paramArr := strings.Split(params, "|")
	if nil != paramArr {
		if paramArr != nil && len(paramArr) > 0 {
			for _, value := range paramArr {
				kv := strings.Split(value, "=")
				if kv != nil && len(kv) > 1 {
					maps[kv[0]] = kv[1]
					keys = append(keys, kv[0])
				}
			}
		}
	}
	if len(keys) > 0 {
		models.Keys[app] = keys
	}

	var key = app + "|" + host + "|" + name

	if len(maps) > 0 {

		lastRecord := models.Rc.LGet(key)

		if lastRecord != nil {
			lastMap := map[string]string{}
			json.Unmarshal(lastRecord.([]byte), &lastMap)

			for k, v := range maps {
				if c, ok := lastMap[k]; ok {
					count, _ := strconv.Atoi(v)
					lastCount, _ := strconv.Atoi(c)
					if lastCount > 0 {
						maps[k+"Rate"] = strconv.Itoa((count - lastCount) / int(interval))
					}
				}
			}
		}

		maps["t"] = fmt.Sprint(time.Now().Unix())

		processRates(key, maps)

		jsonBytes, err := json.Marshal(maps)
		if err == nil {
			models.Rc.LPut(key, jsonBytes)
		}
	}
	this.Data["json"] = "success"
	this.ServeJson()
}

func processRates(key string, maps map[string]string) {
	ratesKey := time.Now().Format("2006-01-02") + "|" + key
	rates, ok := models.Rates[ratesKey]
	if !ok {
		rates = map[string]int{}
		vals := models.Rc.HGetAll(ratesKey)
		for k, v := range vals {
			vi, _ := strconv.Atoi(v)
			rates[k] = vi
		}
	}

	for k, value := range maps {
		//v, _ := strconv.Atoi(value)
		if strings.HasSuffix(k, "Rate") {
			if r, ok := maps[k]; ok {
				v, _ := strconv.Atoi(r)
				if v > 0 {
					maxKey := strings.Replace(k, "Rate", "Max", -1)
					if rate, ok := rates[maxKey]; ok {
						if v > rate {
							rates[maxKey] = v
							models.Rc.HSet(ratesKey, maxKey, value)
						}
					} else {
						rates[maxKey] = v
						models.Rc.HSet(ratesKey, maxKey, value)
					}

					minKey := strings.Replace(k, "Rate", "Min", -1)
					if rate, ok := rates[minKey]; ok {
						if v < rate || rate == 0 {
							rates[minKey] = v
							models.Rc.HSet(ratesKey, minKey, value)
						}
					} else {
						rates[minKey] = v
						models.Rc.HSet(ratesKey, minKey, value)
					}
				}
			}
		}
	}
	models.Rates[ratesKey] = rates
}
